package com.example.sqlitelogin;

import static com.example.sqlitelogin.WeatherActivity.urlClimb;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.os.IBinder;
import android.os.StrictMode;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import com.alibaba.fastjson2.function.impl.ToString;
import com.example.sqlitelogin.service.LocationServer;
import com.example.sqlitelogin.service.UserService;
import com.example.sqlitelogin.tools.HttpGetPost;

import java.io.IOException;
import java.util.List;
import java.util.Locale;


public class LoginActivity extends AppCompatActivity {

    Bundle bundle = new Bundle();
    private String City;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //状态栏中的文字颜色和图标颜色，需要android系统6.0以上，而且目前只有一种可以修改（一种是深色，一种是浅色即白色）
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setContentView(R.layout.activity_login);

        findViews();
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        try {
            String prionce = "Liaoning";
            String city = "Shenyang";
            Log.e("leo", prionce);
            Log.e("leo", city);

//            ServiceConnection serviceConnection = new ServiceConnection() {
//                @Override
//                public void onServiceConnected(ComponentName name, IBinder service) {
//                    LocationServer.LocationBinder binder = (LocationServer.LocationBinder) service;
//                    LocationServer locationService = binder.getService();
//                    // 在这里调用Service中的函数
//                    City=locationService.getCity();
//                    double jingdu=locationService.getLongitude();
//
//                    double weidu=locationService.getLatitude();
//                    Log.e("Service:", City);
//                    Log.e("Service:", ""+jingdu);
//                    Log.e("Service:", ""+weidu);
//                }
//
//                @Override
//                public void onServiceDisconnected(ComponentName name) {}
//            };
//            Intent serviceIntent = new Intent(this, LocationServer.class);
//            bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);

            // 创建LocationManager对象
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// 获取最后一次定位信息
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

// 创建Geocoder对象
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());

            try {
                // 根据经纬度获取地址信息
                List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                if (addresses.size() > 0) {
                    City = addresses.get(0).getLocality();
                    Log.e("Service:", City);
                    // 在这里处理获取到的城市信息
                }
            } catch (IOException e) {
                e.printStackTrace();
            }




            //City="沈阳";
            bundle.putString("loact", City);

//            if (prionce.equals("Jiangxi")) {
//                if (city.equals("Shangrao")) {
//                    bundle.putString("loact", "江西省上饶市");
//                    City = "上饶";
//                } else if (city.equals("Nanchang")) {
//                    bundle.putString("loact", "江西省南昌市");
//                    City = "南昌";
//                }

//            } else if (prionce.equals("Liaoning")) {
//                if (city.equals("Shenyang")) {
//                    bundle.putString("loact", "辽宁省沈阳市");
//                    City = "沈阳";
//                } else if (city.equals("Dalian")) {
//                    bundle.putString("loact", "辽宁省大连市");
//                    City = "大连";
//                } else if (city.equals("Anshan")) {
//                    bundle.putString("loact", "辽宁省鞍山市");
//                    City = "鞍山";
//                } else if (city.equals("Fushun")) {
//                    bundle.putString("loact", "辽宁省抚顺市");
//                    City = "抚顺";
//                } else if (city.equals("Benxi")) {
//                    bundle.putString("loact", "辽宁省本溪市");
//                    City = "本溪";
//                } else if (city.equals("Dandong")) {
//                    bundle.putString("loact", "辽宁省丹东市");
//                    City = "丹东";
//                } else if (city.equals("Jinzhou")) {
//                    bundle.putString("loact", "辽宁省锦州市");
//                    City = "锦州";
//                } else if (city.equals("Yingkou")) {
//                    bundle.putString("loact", "辽宁省营口市");
//                    City = "营口";
//                } else if (city.equals("Fuxin")) {
//                    bundle.putString("loact", "辽宁省阜新市");
//                    City = "阜新";
//                } else if (city.equals("Liaoyang")) {
//                    bundle.putString("loact", "辽宁省辽阳市");
//                    City = "辽阳";
//                } else if (city.equals("Tieling")) {
//                    bundle.putString("loact", "辽宁省铁岭市");
//                    City = "铁岭";
//                } else if (city.equals("Chaoyang")) {
//                    bundle.putString("loact", "辽宁省朝阳市");
//                    City = "朝阳";
//                } else if (city.equals("Panjin")) {
//                    bundle.putString("loact", "辽宁省盘锦市");
//                    City = "盘锦";
//                } else if (city.equals("Huludao")) {
//                    bundle.putString("loact", "辽宁省葫芦岛市");
//                    City = "葫芦岛";
//                }
//            }

            City= City.replace("市", "");


            String jsonStr = "";
            String strUrl = "http://apis.juhe.cn/simpleWeather/query";
            String srtVlaue = "city=" + City + "&key=7745e843fd2ccf00611fccc2a305d205";
            jsonStr = HttpGetPost.sendGet(strUrl, srtVlaue);
            Log.e("leo", jsonStr);
            JSONObject json = JSON.parseObject(jsonStr);

            String temp3 = (String) json.getJSONObject("result").getJSONObject("realtime").get("temperature");
            String daylight = (String) json.getJSONObject("result").getJSONObject("realtime").get("info");
            String direct = (String) json.getJSONObject("result").getJSONObject("realtime").get("direct");
            String power = (String) json.getJSONObject("result").getJSONObject("realtime").get("power");
            String aqi = (String) json.getJSONObject("result").getJSONObject("realtime").get("aqi");

            JSONObject js=json.getJSONObject("result");
            JSONArray gj=js.getJSONArray("future");

            JSONObject getJsonObj = gj.getJSONObject(1);//获取json数组中的第一项

//            JSONArray getJsonArray=new JSONArray(json.getJSONObject("result").getJSONObject("future"));
//            JSONObject getJsonObj = getJsonArray.getJSONObject(0);//获取json数组中的第一项
            String date2=(String) getJsonObj.get("date");
            String temperature2=(String) getJsonObj.get("temperature");
            String weather2=(String) getJsonObj.get("weather");
            String direct2=(String) getJsonObj.get("direct");

//            Log.e("leo",temperature2);
            JSONObject tJsonObj = gj.getJSONObject(2);//获取json数组中的第一项

//            JSONObject tJsonObj = getJsonArray.getJSONObject(1);//获取json数组中的第一项

            String date3=(String) tJsonObj.get("date");
            String temperature3=(String) tJsonObj.get("temperature");
            String weather3=(String) tJsonObj.get("weather");
            String direct3=(String) tJsonObj.get("direct");



            bundle.putString("power",power);
            bundle.putString("aqi",aqi);
            bundle.putString("direct",direct);
            bundle.putString("temp12", temp3);
            bundle.putString("temp34", daylight);

            bundle.putString("date2", date2);
            bundle.putString("temperature2", temperature2);
            bundle.putString("weather2", weather2);
            bundle.putString("direct2", direct2);

            bundle.putString("date3", date3);
            bundle.putString("temperature3", temperature3);
            bundle.putString("weather3", weather3);
            bundle.putString("direct3", direct3);
//            Log.e("leo",power+aqi+direct+daylight+temp3);

        } catch (Exception e) {
            Log.e("leo", "" + e);
        }

    }

    private EditText username;
    private EditText password;
    private Button login;
    private Button register;
    private void findViews() {
        username=(EditText) findViewById(R.id.username);

        password=(EditText) findViewById(R.id.password);
        login=(Button) findViewById(R.id.login);
        register=(Button) findViewById(R.id.register);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=username.getText().toString();
                System.out.println(name);
                String pass=password.getText().toString();
                System.out.println(pass);
                Log.i("TAG",name+"_"+pass);
                UserService uService=new UserService(LoginActivity.this);
                boolean flag=uService.login(name, pass);
                if(flag){
                    Log.i("TAG","登录成功");
                    Toast toast=Toast.makeText(LoginActivity.this, null, Toast.LENGTH_LONG);
                    toast.setText("登录成功");
                    toast.show();
                    bundle.putString("name",name);
                    Intent intent = new Intent(LoginActivity.this,MainActivity.class);

                    intent.putExtras(bundle);
                    startActivity(intent);

                }else{
                    Log.i("TAG","登录失败");
                    Toast toast=Toast.makeText(LoginActivity.this, null, Toast.LENGTH_LONG);
                    toast.setText("登录失败");
                    toast.show();
                }
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });
    }
    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    //判断是否要收起键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        //如果目前得到焦点的这个view是editText的话进行判断点击的位置
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击EditText的事件，忽略它。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上
        return false;
    }

    //隐藏软键盘并让editText失去焦点
    private void hideKeyboard(IBinder token) {
        password.clearFocus();
        if (token != null) {
            //这里先获取InputMethodManager再调用他的方法来关闭软键盘
            //InputMethodManager就是一个管理窗口输入的manager
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}
